<?php
/**
 * Created by MY_MIND.
 * User: WDJ
 * Date: 2018/7/5 0005
 * Time: 15:21
 */

//index模块公共函数

/**
 * WDJ
 * 新建公共函数   createNoncestr  xmlToArray  arrayToXml  curlQuery   getSqlConnec
 */

/**
 * 	作用：产生随机字符串，不长于32位
 */
function createNoncestr( $length = 32 )
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

/**
 * 	作用：将xml转为array
 */
function xmlToArray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * 	作用：array转xml
 */
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val) {
        if($val)
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
    }
    $xml .= "</xml>";
    return $xml;
}

/**
 * 通过CURL发起请求，可以发送数据，可以验证证书
 * @param string $url               请求地址
 * @param string $method            请求方式
 * @param array $data               请求数据
 * @param bool $ssl                 是否要SSL验证
 * @param array $ssl_pem            SSL证书,包括CERT_PEM , KEY_PEM
 * @param int $timeout              最大执行时间
 * return array                     [flag, result]
 */
function curlQuery($url , $method = "GET" , $data = [] , $ssl = false , $ssl_pem = [] , $timeout = 30)
{
    //判断请求地址和请求方式
    if($url == '' || !in_array($method, ['GET', 'POST'])){
        return [false, '请求地址不能为空或者请求方式出错'];
    }

    //初始化curl会话
    $ch =   curl_init();

    //设置curl选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, intval($timeout));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    //是否post请求
    if($method == 'POST'){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //是否SSL验证
    if($ssl){
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $ssl_pem['CERT_PEM']);
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $ssl_pem['KEY_PEM']);
    }

    //得出结果
    $output =   curl_exec($ch);

    if($output){
        curl_close($ch);
        return [true, $output];
    }else{
        return [false, curl_error($ch)];
    }
}

/**
 * 实例化连接SQLServer
 * @param string $database  数据库名称
 * @param string $table     表名
 * @return source   连接SQLServer的资源对象
 */
function getSqlConnec($database = '', $table = '')
{
    if($database == ''){
        return false;
    }
    $config             =   \think\Config::get('sqldatabase');
    $config['database'] =   $database;
    if($table != ''){
        return \think\Db::connect($config)->table($table);
    }
    return  \think\Db::connect($config);
}